#pragma once
#include <iostream>
#include <string>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Common.hpp"

class InetAddr
{
private:
    void Port2Host()
    {
        _port = ::ntohs(_addr.sin_port);
    }
    void Ip2Host()
    {
        char ipbuffer[64];
        const char *ip = ::inet_ntop(AF_INET, &_addr.sin_addr, ipbuffer, sizeof(ipbuffer));
        (void)ip;
    }

public:
    InetAddr()
    {
    }
    InetAddr(const struct sockaddr_in &addr)
        : _addr(addr)
    {
        Port2Host();
        Ip2Host();
    }
    InetAddr(u_int16_t port)
        : _port(port), _ip("")
    {
        _addr.sin_family = AF_INET;
        _addr.sin_port = htons(_port);
        _addr.sin_addr.s_addr = INADDR_ANY;
    }
    bool operator==(const InetAddr& addr)
    {
        return addr._ip == _ip && addr._port == _port; 
    }
    std::string Addr() {  return Ip() + ":" + std::to_string(Port());}
    std::string Ip() { return _ip; }
    uint16_t Port() { return _port; }
    struct sockaddr *SockAddr() { return Conv(&_addr); }
    socklen_t SockLen() { return sizeof(_addr); }

private:

    uint16_t _port;
    std::string _ip;
    struct sockaddr_in _addr;
};
